/**
* Author: fulishang
* Create Time  : 2016年8月4日,下午9:56:32
* Modify Time :
* Desc  : 
*/
package com.sam.si.dc.processor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import com.sam.si.dc.dao.UserDao;
import com.sam.si.dc.domain.User;
import com.sam.si.dc.handler.HousekeepHandler;

@Component
public class DCProcessor {
	private static final Logger LOGGER = Logger.getLogger(DCProcessor.class);
	@Autowired
	private UserDao userDao;

	@Autowired
	private HousekeepHandler housekeepHandler;

	@Value("${dc.input.file.directory}")
	private String inputDir;
	
	public void process(Message<List<Map<Object, Object>>> msg) throws Exception {
		List<Map<Object, Object>> records = msg.getPayload();
		userDao.save(this.batchInsert(records));
		LOGGER.info("Batch Insert done...");
		this.housekeepHandler.fileHousekeep(inputDir);
	}

	public List<User> batchInsert(List<Map<Object, Object>> entities) {
		LOGGER.info("Records size is " + entities.size());
		List<User> users = new ArrayList<>();

		for (Map<Object, Object> map : entities) {
			User user = new User();
			for (Map.Entry<Object, Object> entry : map.entrySet()) {
				if (entry.getKey().toString().toLowerCase().equals("name")) {
					user.setName(entry.getValue().toString());
				} else if (entry.getKey().toString().toLowerCase().equals("email")) {
					user.setEmail(entry.getValue().toString());
				} else if (entry.getKey().toString().toLowerCase().equals("gender")) {
					user.setGender(entry.getValue().toString());
				}
			}
			users.add(user);
		}
		return users;
	}

}
